package com.kingyun.gpsinspection.purificationservice.services.tdm.quartzjob;

import com.kingyun.gpsinspection.purificationservice.common.activiti.ActivitiConstants;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.DutyRecordsMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.DutyRecords;
import com.kingyun.gpsinspection.purificationservice.facade.service.activiti.base.WorkFlowService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时创建干部值班
 * Created by jiangjx on 2017/12/22.
 */
public class CreateDutyRecords extends QuartzJobBean {
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static final String KEY = "scheduling";

    @Autowired
    DutyRecordsMapper dutyRecordsMapper;

    @Autowired
    private WorkFlowService workFlowService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取需要创建的干部值班记录
        List<DutyRecords> list = dutyRecordsMapper.queryNoCreateRows();
        //判定是否到了创建时间,如果日期和当前日期相同表示今天要值班
        list.stream().filter(dutyRecords -> simpleDateFormat.format(dutyRecords.getStartTime()).equals(simpleDateFormat.format(new Date()))).forEach(dutyRecords -> {
            try {
                //发起流程
                Map<String, Object> map = createTask(dutyRecords);
                //修改值班记录状态
                if (map.get("state").toString().equals("true")) {
                    dutyRecords.setIsCreate(1);
                    dutyRecordsMapper.updateByPrimaryKeySelective(dutyRecords);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
        });


    }

    /**
     * 发起流程
     *
     * @param dutyRecords
     */
    private Map<String, Object> createTask(DutyRecords dutyRecords) throws Exception {
        Map variables = new HashMap<>();
        //厂领导
        String[] str = {dutyRecords.getOnDutyId()};
        variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
        //发起流程
        return workFlowService.startProcessInstanceByKey(KEY, dutyRecords.getId(), variables, "admin");
    }
}
